package util

import (
	"bytes"
	"errors"
	"image/color"
	"math/rand"

	"github.com/mojocn/base64Captcha"
)

//configJsonBody json request body.
type configJsonBody struct {
	Id            string
	CaptchaType   string
	VerifyValue   string
	DriverAudio   *base64Captcha.DriverAudio
	DriverString  *base64Captcha.DriverString
	DriverChinese *base64Captcha.DriverChinese
	DriverMath    *base64Captcha.DriverMath
	DriverDigit   *base64Captcha.DriverDigit
}

var store = base64Captcha.DefaultMemStore

var defaultType = "string"
var defaultLen = 4
var defaultDriverString = base64Captcha.DriverString{
	Height:          60,
	Width:           160,
	NoiseCount:      0,
	ShowLineOptions: 4,
	Length:          defaultLen,
	Source:          "",
	BgColor:         &color.RGBA{0, 0, 0, 0},
	Fonts:           []string{"Flim-Flam.ttf"},
}
var charList = []byte{
	'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
	'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
}

func GenerateCaptchaRand() (string, string, error) {
	var build bytes.Buffer
	for i, len := 0, len(charList); i < defaultLen; i++ {
		b := charList[rand.Intn(len)]
		build.WriteByte(b)
	}
	return GenerateCaptcha(build.String())
}

func GenerateCaptcha(source string) (string, string, error) {
	len := len(source)
	if len < defaultLen {
		return "", "", errors.New("字符数小于" + string(defaultLen))
	}
	var str string
	if len > defaultLen {
		str = string(source[0:defaultLen])
	} else {
		str = string(source)
	}
	defaultDriverString.Source = str
	return GenerateCaptchaByDriver(defaultDriverString.ConvertFonts())
}

func GenerateCaptchaByDriver(driver base64Captcha.Driver) (id, b64s string, err error) {
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, err = c.Generate()
	return
}

func CaptchaVerify(id, value string) (bool, error) {
	if len(id) > 0 && len(value) > 0 {
		return store.Verify(id, value, false), nil
	}
	return false, errors.New("id or value is not a string")
}
